<template>
  <el-form :model="user" :rules="rules" ref="form">
    <el-form-item label="账号" prop="username">
      <el-input v-model.trim="user.username" readonly/>
    </el-form-item>
    <el-form-item label="姓名" prop="name">
      <el-input v-model.trim="user.name" />
    </el-form-item>
    <el-form-item label="性别">
      <br/>
      <el-select v-model="user.sex" placeholder="请选择">
        <el-option v-for="item in sexOptions" :key="item" :label="item" :value="item"> </el-option>
      </el-select>
    </el-form-item> 
    <el-form-item>
      <el-button type="primary" @click="submit('form')">确定</el-button>
    </el-form-item>
  </el-form>
</template>
<script>
import { modifyMyInfo } from '@/api/admin/user/index'
export default {
  data() {
    return {
      form: {
        username: undefined,
        name: undefined,
        sex: '男'
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入用户',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ],
        username: [
          {
            required: true,
            message: '请输入账户',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 20,
            message: '长度在 3 到 20 个字符',
            trigger: 'blur'
          }
        ]
      },
      sexOptions: ['男', '女']
    }
  },
  props: {
    user: {
      type: Object,
      default: () => {
        return {}
      }
    }
  }, 
  created() {
      this.form.username = this.user.username;
      this.form.sex = this.user.sex;
      this.form.name = this.user.name; 
  },
  methods: {
    submit(formName) {
      //验证表单
      const set = this.$refs;
      set[formName].validate(valid => {
        if (valid) {
           this.form.username = this.user.username;
           this.form.name = this.user.name;
           this.form.sex = this.user.sex;
           modifyMyInfo(this.form).then(response => {
           if(response.status === 0){
              this.$message.success('修改成功');
           }
          else{
            this.$message.error(response.message);
          }
         });
        } else {
          return false;
        }
      });
    }
  }
}
</script>
